<?php

require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\activity\CouponConfig as mCouponConfig;
use Biz\model\theParagraph\Store as mStore;
use Biz\model\trade\CustomizePayWay as mCustomizePayWay;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderExtend as mOrderExtend;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\pockets\constInterface\PayConfig;
use Biz\service\Goods as sGoods;
use Biz\tools\ShopArea;
use Doraemon\model\Category as mCategory;

$end_date = date('Y-m-d');
$start_date = date("Y-m-d", strtotime($end_date) - (86400));

$OrderInfos = mOrder::getOrderInfoList([
    'addtime[>]' => $start_date,
    'addtime[<]' => $end_date,
], [], ['addtime' => 'ASC'], true);

$OrderInfos = $OrderInfos ? $OrderInfos : [];
$orderNos = $OrderInfos ? array_column($OrderInfos, 'order_no') : [];
$uids = $OrderInfos ? array_column($OrderInfos, 'uid') : [];
$shop_uids = $OrderInfos ? array_column($OrderInfos, 'shop_id') : [];
$uids = array_merge($uids, $shop_uids);
$userinfos = \Doraemon\service\User::getUsers($uids);
$couponIds = $OrderInfos ? array_column($OrderInfos, 'coupon_id') : [];

$couponCodes = [];
if ($couponIds) {
    $couponList = mCouponConfig::select(['coupon_id', 'coupon_code'], ['coupon_id' => $couponIds]);
    foreach ($couponList as $row) {
        if ($row['coupon_code']) {
            $couponCodes[$row['coupon_id']] = $row['coupon_code'];
        }
    }
}

$orderGoodsInfos = $orderNos ? mOrderGoods::getFieldsByOrderNo($orderNos) : [];
$goodsIds = array_column($orderGoodsInfos, 'goods_id');
$goodsList = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_BASE);
$categoryIds = array_column($goodsList, 'category_id');
$categoryIds = array_merge($categoryIds, array_column($goodsList, 'second_category_id'));
$categoryInfos = mCategory::selectCategorys($categoryIds);
$isPayed = [];
$payInfos = mOrder::getOrderInfoList([
    'GROUP' => 'uid',
    'status[!]' => [mOrder::STATUS_NORMAL],
    'pay_way[!]' => '0',
    'uid' => $uids,
    'pay_time[<]' => $start_date,
], [], [], false, 'uid');
$isPayed = $payInfos ? $payInfos : [];

$orderGoodsInfosGrpByOrderNo = [];
foreach ($orderGoodsInfos as $orderGoodsInfo) {
    $orderGoodsInfosGrpByOrderNo[$orderGoodsInfo['order_no']][] = $orderGoodsInfo;
}

$orderExtendResult = mOrderExtend::getOrderListByOrderNos($orderNos);
$orderExtendList = [];
$storeIds = array_column($orderExtendResult, 'store_id');
$storeIds = array_unique($storeIds);
foreach ($orderExtendResult as $row) {
    $orderExtendList[$row['order_no']] = $row;
}
$storeResult = mStore::getStoresByIds($storeIds);
$storeList = [];
foreach ($storeResult as $row) {
    $storeList[$row['id']] = $row['title'];
}

$customizePayList = [];
$customizePayResult = mCustomizePayWay::select(['order_no', 'pay_type', 'pay_amount', 'remark'], ['order_no' => $orderNos]);
foreach ($customizePayResult as $row) {
    $payType = $row['pay_type'];
    if ($payType) {
        $customizePayList[$row['order_no']]['pay_way'] = mCustomizePayWay::PAY_TYPE_DESC[$payType];
    }
    $customizePayList[$row['order_no']]['pay_type'] = $row['pay_type'];
    $customizePayList[$row['order_no']]['pay_amount'] = $row['pay_amount'];
    $customizePayList[$row['order_no']]['remark'] = $row['remark'];
}

$title = [
    '订单号',
    '商品id',
    '商家uid',
    '商家名称',
    '商品名称',
    'skuid',
    '商品型号',
    '数量',
    '单价',
    '总金额',
    '实付金额',
    '运费',
    '订单状态',
    '下单用户UID',
    '下单用户',
    '是否是首单',
    '用户注册时间',
    '收货地址所在区域',
    '下单时间',
    '活动类型',
    '平台卷抵扣',
    '平台卷ID',
    '优惠码',
    '积分抵扣',
    '店铺优惠',
    '支付方式',
    '一级类目ID',
    '一级类目名称',
    '二级类目ID',
    '二级类目名称',
    '订单来源',
    '订单归属地',
    '订单渠道',
];
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR;
$file_path = $dir . "orderinfolist" . $start_date . "_" . $end_date . ".csv";

//file_put_contents($file_path, implode(",", $title) . "\r\n", FILE_APPEND);
$fp = fopen($file_path, 'w');
fputcsv($fp, $title);

$orders = [];

foreach ($OrderInfos as $orderInfo) {
    $orderGoodsInfos = $orderGoodsInfosGrpByOrderNo[$orderInfo['order_no']];
    $storeTitle = '北京';
    $isDesigner = false;
    if ($orderExtendList && isset($orderExtendList[$orderInfo['order_no']])) {
        $storeId = $orderExtendList[$orderInfo['order_no']]['store_id'];
        $isDesigner = $orderExtendList[$orderInfo['order_no']]['is_designer'];
        if ($storeId) {
            $storeTitle = $storeList[$storeId];
        }
    }
    $orderNo = $orderInfo['order_no'];
    preg_match('/^BJ./', $orderNo, $res);
    if ($res) {
        if (isset($customizePayList[$orderNo])) {
            //北京祥云小镇只是 “北京pos-xxx”和北京现金
            if (!in_array($customizePayList[$orderNo]['pay_type'], [mCustomizePayWay::PAY_TYPE_BJ_POS_ALIPAY, mCustomizePayWay::PAY_TYPE_BJ_POS_BANKCARD, mCustomizePayWay::PAY_TYPE_BJ_POS_WECHAT, mCustomizePayWay::PAY_TYPE_BJ_CASH])) {
                $storeTitle = '北京';
            }
        } else {
            $storeTitle = '北京';
        }
    }
    $payWay = '';
    if (in_array($orderInfo['pay_way'], PayConfig::_ALIPAY_PAY_WAYS_LIST)) {
        $payWay = '支付宝';
    } else if (in_array($orderInfo['pay_way'], PayConfig::_WECHAT_PAY_WAYS_LIST)) {
        $payWay = '微信';
    } else if ($orderInfo['pay_way'] == PayConfig::_PAY_WAYS_CUSTOMIZE_PAY_WAY) {
        $payWay = '线下支付';
        if (isset($customizePayList[$orderNo])) {
            $payWay .= '-' . $customizePayList[$orderNo]['pay_way'];
        }
    }
    foreach ($orderGoodsInfos as $orderGoodsInfo) {
        if (!in_array($orderInfo['shop_id'], \Biz\model\GoodsBasicInfo::$testShopIds)) {
            $content = [
                $orderInfo['order_no'],
                $orderGoodsInfo['goods_id'],
                $orderInfo['shop_id'],
                isset($userinfos[$orderInfo['shop_id']]) ? $userinfos[$orderInfo['shop_id']]['nick'] : '',
                $orderGoodsInfo['title'],
                $orderGoodsInfo['sku_id'],
                $orderGoodsInfo['sku_desc'],
                $orderGoodsInfo['buy_num'],
                $orderGoodsInfo['buy_price'],
                $orderGoodsInfo['goods_amount'],
                $orderGoodsInfo['pay_amount'],
                in_array($orderInfo['order_no'], $orders) ? '' : $orderInfo['shipping_amount'],
                mOrder::$statusDesc[$orderInfo['status']],
                $orderInfo['uid'],
                $userinfos[$orderInfo['uid']]['nick'],
                in_array($orderInfo['uid'], $isPayed) ? '否' : '是',
                date("Y-m-d H:i:s", $userinfos[$orderInfo['uid']]['addtime']),
                ShopArea::locationId2String($orderInfo['consignee_province'] . ", " . $orderInfo['consignee_city']),
                $orderInfo['addtime'],
                $orderGoodsInfo['promo_type'] ? ActivityInfo::ACTIVITY_TYPES_MAPS[$orderGoodsInfo['promo_type']] : '',
                $orderGoodsInfo['coupon_amount'],
                $orderGoodsInfo['coupon_id'],
                ($couponCodes && isset($couponCodes[$orderGoodsInfo['coupon_id']])) ? $couponCodes[$orderGoodsInfo['coupon_id']] : '',
                $orderGoodsInfo['integral_amount'],
                sprintf("-%.2f", $orderGoodsInfo['s_coupon_amount']),
                $payWay,
                $goodsList[$orderGoodsInfo['goods_id']]['category_id'],
                $categoryInfos[$goodsList[$orderGoodsInfo['goods_id']]['category_id']]['cate_name'],
                $goodsList[$orderGoodsInfo['goods_id']]['second_category_id'],
                $categoryInfos[$goodsList[$orderGoodsInfo['goods_id']]['second_category_id']]['cate_name'],
                mOrder::$fromSource[$orderInfo['from_source']],
                $storeTitle,
                $isDesigner ? '设计师' : '普通',
            ];
            fputcsv($fp, $content);
        }
        $orders[] = $orderInfo['order_no'];
    }
}

fclose($fp);
$sendMail = [
    'biz-rd@haohaozhu.com',
    'gmv@haohaozhu.com'
];
\Biz\tools\Mail::send($sendMail, $start_date . " 订单信息", '订单信息', $file_path);

